package org.tim.websocket;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import lombok.var;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.tim.common.config.TimConfig;
import org.tim.websocket.chat.*;
import org.tim.websocket.protocol.WebSocketProtocol;
import org.tio.websocket.server.WsServerConfig;

import java.net.URI;

public class WebSocketConfiguration {

    @Bean
    public TimWebSocketHandler timWebSocketHandler() {
        var heartbeatPool = new NioEventLoopGroup(0, new ThreadFactoryBuilder().setNameFormat("websocket-heartbeat-pool-%s").build());
        var workPool = new NioEventLoopGroup(0, new ThreadFactoryBuilder().setNameFormat("websocket-work-pool-%s").build());
        return new TimWebSocketHandler(heartbeatPool, workPool);
    }

    @Bean
    public WsServerConfig wsServerConfig(TimConfig timConfig) {
        var bind = URI.create(timConfig.getBind());
        return new WsServerConfig(bind.getPort());
    }

    @Bean
    public WebSocketProtocol webSocketProtocol(WsServerConfig wsServerConfig, TimWebSocketHandler timWebSocketHandler) {
        return new WebSocketProtocol(wsServerConfig, timWebSocketHandler);
    }

    @Bean
    public DefaultPrivateChatKit defaultPrivateChatKit() {
        return new DefaultPrivateChatKit();
    }

    @Bean
    public PrivateAckChatKit privateAckChatKit() {
        return new PrivateAckChatKit();
    }

    @Bean
    public PrivateReadChatKit privateReadChatKit() {
        return new PrivateReadChatKit();
    }

    @Bean
    public PrivateTextChatKit privateTextChatKit() {
        return new PrivateTextChatKit();
    }

    @Bean
    public EventLoopGroup eventLoopGroup() {
        return new NioEventLoopGroup(0, new ThreadFactoryBuilder().setNameFormat("websocket-accept-pool-%s").build());
    }
}
